<?php

namespace App\Services;

use App\Common\Libs\ArrayHelper;
use App\Common\Libs\Dispatch\Queue;
use App\Consts\GlobalConst;
use App\Consts\GlobalDynamicConst;
use App\Consts\GlobalQueueConst;
use App\Exceptions\Error;
use App\Formats\DynamicFormat;
use App\Jobs\Controller\DynamicJob;
use App\Models\UserAttention;
use Illuminate\Support\Facades\DB;

class DynamicService extends BaseService
{
    public $_repository;

    public function __construct()
    {
        parent::__construct();
        $this->_repository = repository()->DynamicRepository;
    }

    /**
     * 关注的动态列表
     * @param $searchParams
     * @return array
     */
    public function getAttentionDynamicList($searchParams)
    {
        // 获取关注数据
        $dataProvider = $this->_repository->getAttentionDynamicList($searchParams);
        $pagination = $this->getPagination();
        $attentions = $dataProvider->get();

        // 格式化结果，乱序
        $list = formats()->DynamicFormat->formatRecommendSystemList($attentions, $searchParams['current_user_id'], DynamicFormat::SQUARE_ATTENTION_LIST);

        // 对结果进行排序，注意此处排序需和获取关注数据一致
        $list = ArrayHelper::multisort($list, ['apply_at'], SORT_DESC);

        return self::outputMoreList($dataProvider, $pagination, $list);
    }

    /**
     * 用户动态列表
     * @param $searchParams
     * @return array
     */
    public function getUserDynamicList($searchParams)
    {
        // 获取用户动态数据
        $dataProvider = $this->_repository->getUserDynamicList($searchParams);
        $pagination = $this->getPagination();
        $dynamics = $dataProvider->get();

        $list = formats()->DynamicFormat->formatRecommendSystemList($dynamics, $searchParams['current_user_id'], DynamicFormat::USER_DYNAMIC_LIST);

        // 对结果进行排序，注意此处排序需和获取用户动态数据一致
        $list = ArrayHelper::multisort($list, ['created_at'], SORT_DESC);

        return self::outputMoreList($dataProvider, $pagination, $list);
    }

    /**
     * 刪除动态
     * @param $id
     * @param $userId
     * @return mixed
     */
    public function delDynamic($dynamicId, $userId)
    {
        // 开启事务删除动态
        DB::beginTransaction();
        try {
            $dynamic = $this->_repository->getDynamicByUserId($dynamicId, $userId);
            if (!$dynamic) {
                return Error::handle('Dynamic not found');
            }

            // 删除动态记录
            $this->_repository->delDynamic($dynamic);

            $followerIdArr = repository()->RelationshipRepository->getUserAllFollowersIdArr($userId);
            $followerIdArr = ArrayHelper::merge(ArrayHelper::toArray($followerIdArr), [$userId]);
            foreach ($followerIdArr as $followerId) {
                UserAttention::getModel($followerId)
                    ->where('user_attention_id', $userId)
                    ->where('user_id', $followerId)
                    ->whereIn('target_id', (array)$dynamic->dynamic_id)
                    ->update(['is_deleted' => GlobalConst::IS_DELETED, 'is_view' => GlobalDynamicConst::IS_NOT_VIEW]);
            }

            if ($dynamic->target_type == GlobalConst::TARGET_TYPE_NOTE) {
                service()->NoteDataService->onDel([
                    'id' => $dynamic->target_id,
                    'user_id' => $userId,
                ]);
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            return Error::throw($e);
        }
    }

    /**
     * @param $dynamicId
     * @return array
     */
    public function getDynamic($dynamicId)
    {
        $dynamic = $this->_repository->getDynamic($dynamicId);
        if (!$dynamic) {
            return Error::handle('Dynamic is empty');
        }

        $user = repository()->UserRepository->getUserByUserId($dynamic->user_id);

        $result = [];
        if ($dynamic->target_type == GlobalConst::TARGET_TYPE_ARTICLE) {
            $article = $dynamic->article;
            $result['article'] = ArrayHelper::merge($article->commonFormat(), service()->ArticleService->getArticleMoreFields($article, $dynamic->user_id));
        }

        if ($dynamic->target_type == GlobalConst::TARGET_TYPE_NOTE) {
            $result['note'] = service()->NoteService->getNoteMoreFields($dynamic->note);
        }

        $result = ArrayHelper::merge($result, [
            'user' => $user ? $user->commonFormat() : (object)[],
        ]);

        return ArrayHelper::merge($dynamic->commonFormat(), $result);
    }

    /**
     * 新增【一键收藏文章】【笔记】后，创建一条动态
     * @param $queueMessageBody
     * @param int $delay
     * @return \Illuminate\Foundation\Bus\PendingDispatch
     */
    public function addDynamicByTarget($queueMessageBody, $delay = 0)
    {
        return Queue::getInstance(DynamicJob::class)
            ->push($queueMessageBody, GlobalQueueConst::DYNAMIC_CREATE, $delay);
    }

    /**
     * 删除【一键收藏文章】、【笔记】后
     *  1. 删除[feed_dynamic]
     *  2. 删除[user_attention]
     *  3. 更新用户动态计数
     *  4. 记录删除动态日志[log_count_]
     * @param $queueMessageBody
     */
    public function delDynamicByArticle($queueMessageBody)
    {
        return Queue::getInstance(DynamicJob::class)
            ->push($queueMessageBody, GlobalQueueConst::DYNAMIC_DEL_BY_ARTICLE);
    }

    /**
     * 删除【一键收藏文章】、【笔记】后
     *  1. 删除[feed_dynamic]
     *  2. 删除[user_attention]
     *  3. 更新用户动态计数
     *  4. 记录删除动态日志[log_count_]
     * 注意：
     *  1. 如果是公开的笔记才更新用户动态计数
     * @param $queueMessageBody
     */
    public function delDynamicByNote($queueMessageBody)
    {
        return Queue::getInstance(DynamicJob::class)
            ->push($queueMessageBody, GlobalQueueConst::DYNAMIC_DEL_BY_NOTE);
    }
}
